package net.ghy.statistics;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import net.ghy.statistics.Byte_File_Object;
import net.bat.util.Cfg;

public class ExcelService extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
    private static final String CONTENT_TYPE = "application/vnd.ms-excel;charset=UTF-8";
	private static final String DATE_FORMAT = "yyyy-MM-dd-hh-mm-ss";
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ExportExcel ee = Cfg.getContext().getBean("ExportExcel",
				ExportExcel.class);
		File file = ee.buildDestPath();
		String type = request.getParameter("type");
		String start = request.getParameter("start");
		String end = request.getParameter("end");
		String uid = request.getParameter("uid");//add null check
		String bxtype = request.getParameter("bxtype");
		// 输出文件流
		try {
			if (type.equals("Q")) {
				try {
					ee.ExportQY(file,start,end);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else if (type.equals("A")) {
				ee.ExportAge(file,start,end);
			} else if (type.equals("J")) {
				ee.ExportJhsy(file,start,end);
			} else if (type.equals("Y")) {
				ee.ExportDbyw(file,start,end);
			} else if (type.equals("DQ")) {
				ee.ExportDbqx(file,start,end);
			} else if (type.equals("S")) {
				ee.ExportSpecial(file,start,end);
			}else
				ee.ExportUser(file,uid,bxtype,start,end);
			
		} catch (RowsExceededException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WriteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		response.setContentType(CONTENT_TYPE);
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
		String filename = sdf.format(Calendar.getInstance().getTime())
				.toString() + "_obj.xls"; // 2010-03-03:02:43:39_obj.xls
		response.setHeader("Content-Disposition", "attachment;filename="
				+ filename);
		OutputStream out = response.getOutputStream(); // 将 WritableWorkbook
		ee.exportExcel(out);
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			doGet(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}